// 引入必要的模块
var express = require("express");
var router = express.Router();
// var http = require("http").createServer(router);
// var { Server } = require("socket.io");
var { DemoUser, DemoFriendList, DemoChatRecord } = require("../model/fwc");
const fs = require("fs");
const mongoose = require("mongoose");
const WebSocket = require("ws"); // 引入 ws 库

const wss = new WebSocket.Server({ port: 3333 });

// 图片上传 WebSocket
wss.on("connection", (ws) => {
  console.log("WebSocket连接已建立");
  let fileName = ""; // 保存文件名
  let totalChunks = 0; // 总块数
  let receivedChunks = 0; // 已接收到的块数
  let writableStream = null; // 可写流用于写入文件

  ws.on("message", async (message) => {
    if (Buffer.isBuffer(message)) {
      if (fileName === "") {
        const metaBuffer = message.toString();
        const meta = JSON.parse(metaBuffer);

        // 提取文件名和总块数
        fileName = meta.fileName;
        totalChunks = meta.totalChunks;

        // 创建可写流，用于写入文件
        writableStream = fs.createWriteStream(`./uploads/${fileName}`);
      } else {
        // 将文件块数据写入可写流
        writableStream.write(message);
        receivedChunks++;

        let progress = 0;

        // 判断是否已接收所有块
        if (receivedChunks === totalChunks) {
          // 关闭可写流，保存文件
          writableStream.end();

          // 假设我们使用'/images'作为静态资源路径
          const fileUrl = `http://localhost:3088/uploads/${fileName}`;

          await DemoUser.updateOne(
            { _id: "661bb16f4369f681408eee21" }, // 查找条件，替换为实际的用户ID
            { $set: { avatar: fileUrl } } // 更新操作，将avatar字段设为新地址
          );
          // 重置相关变量
          writableStream = null;
          fileName = "";
          totalChunks = 0;
          receivedChunks = 0;
          progress = 100;
        } else {
          progress = Math.round((receivedChunks / totalChunks) * 100);
        }
        ws.send(JSON.stringify({ type: "progress", progress }));
      }
    }
  });

  ws.on("error", (error) => {
    console.error("WebSocket错误:", error);

    // 如果可写流存在，则关闭可写流
    if (writableStream) {
      writableStream.end();
      writableStream = null;
    }
  });

  // 监听单个WebSocket连接的关闭事件
  ws.on("close", () => {
    console.log("WebSocket连接已关闭");
  });
});

// 模拟注册
router.post("/addUser", async function (req, res, next) {
  const { username, password } = req.body;

  // 先检查用户名是否已存在
  const existingUser = await DemoUser.find({ username });

  let data = {
    userId: existingUser[0]._id,
    username: existingUser[0].username,
    avatar: existingUser[0].avatar,
  };
  if (existingUser.length > 0) {
    return res.send({
      code: 400,
      msg: "用户名已存在",
      data,
    });
  }

  // 用户名未被使用，进行注册
  const newUser = await DemoUser.create({
    username,
    password,
    avatar: "https://fastly.jsdelivr.net/npm/@vant/assets/cat.jpeg",
  });
  let data2 = {
    id: newUser._id,
    username: newUser.username,
    avatar: newUser.avatar,
  };

  res.send({
    code: 200,
    msg: "注册成功",
    data: data2,
  });
});

// 添加好友
router.post("/add-friend", async (req, res) => {
  try {
    const { userId, friendId, friendNickname, friendAvatar } = req.body;

    // 验证输入数据
    if (
      !mongoose.Types.ObjectId.isValid(userId) ||
      !mongoose.Types.ObjectId.isValid(friendId)
    ) {
      return res.status(400).json({ error: "用户ID无效" });
    }
    if (!friendNickname || typeof friendNickname !== "string") {
      return res.status(400).json({ error: "好友昵称无效" });
    }

    // 创建新的好友条目
    await DemoFriendList.create({
      userId: userId,
      friendId: friendId,
      friendNickname: friendNickname,
      friendAvatar: friendAvatar,
    });

    return res.status(201).json({ message: "成功添加好友" });
  } catch (error) {
    console.error(error);
    return res.status(500).json({ error: "添加好友时发生错误" });
  }
});

// 获取好友列表
router.get("/getFriendListById/:id", async function (req, res, next) {
  const id = req.params.id;
  console.log(id);
  let data = await DemoFriendList.find({ userId: id });
  res.send({
    msg: "查询成功",
    data,
  });
});

// 添加聊天记录
router.post("/add-chat-record", async (req, res) => {
  try {
    const { content, senderId, receiverId } = req.body;

    if (!senderId || !receiverId || !content) {
      return res.send({ error: "Missing required fields" });
    }

    const newChatRecord = new DemoChatRecord({
      content,
      senderId,
      receiverId,
      timestamp: new Date(),
    });

    await newChatRecord.save();

    res.send({
      code: 200,
      msg: "添加聊天记录成功",
    });
  } catch (error) {
    console.error("Error adding chat record:", error);
    res.send({
      code: 200,
      msg: "添加聊天记录失败",
    });
  }
});

// 查询聊天记录
router.get("/chat-records", async (req, res) => {
  try {
    const { senderId, receiverId } = req.query;

    // 验证用户ID是否存在
    if (!senderId || !receiverId) {
      return res.send({ error: "Invalid or missing user IDs" });
    }

    // 查询指定用户间的聊天记录
    const chatRecords = await DemoChatRecord.find({
      $or: [
        { senderId: senderId, receiverId: receiverId },
        { senderId: receiverId, receiverId: senderId },
      ],
    }).sort({ timestamp: -1 });

    res.send({
      code: 200,
      msg: "查询聊天记录成功",
      data: chatRecords,
    });
  } catch (error) {
    console.error("Error fetching chat records:", error);
    res.send({ error: "Failed to fetch chat records" });
  }
});

router.post("/add-user", async (req, res) => {
  const { username, password, nickname } = req.body;
  const avatar = "https://fastly.jsdelivr.net/npm/@vant/assets/cat.jpeg";
  let data = await DemoUser.create({
    username,
    password,
    nickname,
    avatar,
  });
  res.send({
    code: 200,
    msg: "注册成功",
    data,
  });
});

router.get("/get-user", async (req, res) => {
  let data = await DemoUser.find();

  res.send({
    code: 200,
    msg: "查询成功",
    data,
  });
});

// 初始化 WebSocket 服务器
// const io = new Server(http, { cors: { origin: "*" } }); // CORS 设置允许跨域访问
// const port = 3334;
// http.listen(port, () => {
//   console.log(`Socket.IO server started on port ${port}`);
// });

// Socket.IO 事件处理器
// io.on("connection", (socket) => {
//   console.log("Socket.IO 连接已建立");

//   socket.on("sendMessage", async (data) => {
//     // 在这里处理数据，例如存储到数据库或转发给其他客户端
//     // 解析数据，提取必要字段
//     const { content, senderId, receiverId } = data;
//     try {
//       // 校验数据并保存聊天记录
//       const newChatRecord = new DemoChatRecord({
//         content,
//         senderId,
//         receiverId,
//         timestamp: new Date(),
//       });
//       let data = await newChatRecord.save();
//       let NewData = {
//         id: data._id,
//         content: data.content,
//         senderId: data.senderId,
//         receiverId: data.receiverId,
//         timestamp: data.timestamp,
//       };

//       // 向客户端发送确认消息已接收的响应
//       socket.emit("messageReceived", {
//         code: 200,
//         msg: "消息已接收",
//         data: NewData,
//       });
//     } catch (error) {
//       console.error("Error adding chat record:", error);
//       socket.emit("messageReceived", { code: 200, msg: "添加聊天记录失败" });
//     }

//     // 可以选择向客户端回应数据，比如确认消息已接收
//     socket.emit("messageReceived", {
//       status: "success",
//       message: "Message received by server!",
//     });
//   });
// });

module.exports = router;
// module.exports.io = io; // 为了让其他地方也能访问到 Socket.IO 服务器实例
